package com.zeen.wima.update;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.IBinder;

import com.zeen.wima.R;

public class Updater extends Service {

	private static ArrayList<AppInfo> _mNeUpdates = new ArrayList<AppInfo>();

	public static ArrayList<AppInfo> getNewUpdates() {
		return _mNeUpdates;
	}

	private String _mUrl = "http://zen-mobi.com/iphone/update.php";

	
	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		checkNewUpdate();
	}

	/**
	 * 检查程序更新
	 * 
	 * 
	 */
	private void checkNewUpdate() {
		new Thread(new Runnable() {
			public void run() {
				try {
					if (find() && _mNeUpdates.size() > 0) {
						NotificationManager mNotificationManager = (NotificationManager) Updater.this
								.getSystemService(Context.NOTIFICATION_SERVICE);

						long when = System.currentTimeMillis();
						Intent notificationIntent = new Intent(Updater.this,
								InstallList.class);
						notificationIntent
								.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
						notificationIntent
								.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						PendingIntent contentIntent = PendingIntent
								.getActivity(Updater.this, 0,
										notificationIntent, 0);
						Notification notification = new Notification(
								R.drawable.icon, getResources().getString(
										R.string.notify_update_title), when);
						notification.defaults = android.app.Notification.FLAG_AUTO_CANCEL;
						notification.setLatestEventInfo(
								Updater.this,
								getResources().getString(
										R.string.notify_update_title),
								getResources().getString(
										R.string.notify_update_description),
								contentIntent);
						notification.flags |= android.app.Notification.DEFAULT_ALL;
						mNotificationManager.notify(1, notification);
					}
				} catch (Exception e) {

				}
			}
		}).start();
	}

	/**
	 * @author: Jacky
	 * @date: 2010-09-27
	 * @brief: 更新插件
	 */
	private boolean find() throws Exception {
		HttpParams httpParameters = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParameters, 15 * 1000);
		HttpConnectionParams.setSoTimeout(httpParameters, 30 * 1000);
		HttpClient client = new DefaultHttpClient(httpParameters);
		String googleApi = hasGoogleMapApi() ? "1" : "0";
		client.getParams().setParameter(
				HttpProtocolParams.HTTP_CONTENT_CHARSET, "UTF-8");
		String param = "model=" + Uri.encode(android.os.Build.MODEL) + "&sdk="
				+ Uri.encode(android.os.Build.VERSION.SDK) + "&release="
				+ Uri.encode(android.os.Build.VERSION.RELEASE) + "&googleApi="
				+ googleApi;

		String url = _mUrl + "?" + param;
		HttpGet httpRequest = new HttpGet(url);
		String jsonResponse = "";
		HttpResponse httpResponse = client.execute(httpRequest);
		if (httpResponse.getStatusLine().getStatusCode() == 200) {
			jsonResponse = EntityUtils.toString(httpResponse.getEntity());
			if (jsonResponse.endsWith("0")) {
				return false;
			} else {
				try {
					JSONArray founds = new JSONArray(jsonResponse);
					_mNeUpdates.clear();
					for (int i = 0; i < founds.length(); i++) {
						JSONObject item = founds.getJSONObject(i);
						AppInfo found = new AppInfo(item.getString("name"),
								item.getInt("ver"), item.getString("url"),
								item.getString("packageName"),
								item.getString("desc"), item.getInt("size"));
						if (needInstall(found)) {
							_mNeUpdates.add(found);
						}
					}
					return true;
				} catch (Exception e) {
					return false;
				}
			}
		} else {
			return false;
		}
	}

	protected boolean hasGoogleMapApi() {
		String path = "/system/framework/com.google.android.maps.jar";
		File fileName = new File(path);
		return fileName.exists();
	}

	/**
	 * @author: Jacky
	 * @date: 2010-09-27
	 * @brief: 查找是否需要安装
	 */
	private boolean needInstall(AppInfo p) {
		PackageManager pm = this.getPackageManager();
		List<PackageInfo> packs = pm.getInstalledPackages(0);
		for (int i = 0; i < packs.size(); i++) {
			PackageInfo pi = packs.get(i);
			String pName = pi.packageName;
			int verCode = pi.versionCode;
			if (p.getPackageName().endsWith(pName)) {
				if (verCode >= p.getVersion())
					return false;

			}
		}
		return true;
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}
}
